package net.itgoo.parkingpay.ui.edit;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.lufficc.stateLayout.StateLayout;

import net.itgoo.parkingpay.R;
import net.itgoo.parkingpay.rest.model.ParkingCardModel;
import net.itgoo.parkingpay.vendor.widget.fragment.ParkingBaseFragment;
import net.itgoo.parkingpay.vendor.widget.recyclerview.flexibledivider.HorizontalDividerItemDecoration;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import hk.ids.gws.android.sclick.SClick;

import static net.itgoo.parkingpay.ui.main.ParkingMainFragment.PARKING_ACTION_SHOW_PLATE_INFO;

public class ParkingEditChildFragment extends ParkingBaseFragment implements ParkingEditContract.View {

    public static final String PARKING_ACTION_REFRESH_PLATE = "parking_action_refresh_plate";

    private ParkingEditContract.Presenter mPresenter;
    private SVProgressHUD mHUD;
    private RecyclerView mRecyclerView;
    private StateLayout mStateLayout;
    private ParkingEditAdapter mAdapter;

    public ParkingEditChildFragment() {
        // Required empty public constructor
    }

    public static ParkingEditChildFragment newInstance() {
        return new ParkingEditChildFragment();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mPresenter != null) {
            mPresenter.start();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(PARKING_ACTION_REFRESH_PLATE);
        getActivity().registerReceiver(mReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.stop();
        }
    }

    @Override
    public void setPresenter(ParkingEditContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    protected int getLayoutResourceID() {
        return R.layout.parking_fragment_edit_child;
    }

    @Override
    protected void initUI(Bundle savedInstanceState) {
        initViews();
        initHUD();
        initRecyclerView();
        initStateLayout();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mPresenter.getData();
    }

    private void initViews() {
        View contentView = getContentView();
        mStateLayout = contentView.findViewById(R.id.parking_fragment_edit_child_sl);
        mRecyclerView = contentView.findViewById(R.id.parking_fragment_edit_child_rv);
        contentView.findViewById(R.id.parking_fragment_edit_child_add_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!SClick.check(SClick.BUTTON_CLICK)) return;

                mPresenter.openPlateEdit(-1);
            }
        });
    }

    private void initHUD() {
        mHUD = new SVProgressHUD(getActivity());
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).build());

        mAdapter = new ParkingEditAdapter(getActivity());
        mAdapter.setOnItemClickListener(new ParkingEditAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (!SClick.check(SClick.BUTTON_CLICK)) return;

                mPresenter.openItem(position);
            }

            @Override
            public void onItemEdit(int position) {
                if (!SClick.check(SClick.BUTTON_CLICK)) return;

                mPresenter.openPlateEdit(position);
            }

            @Override
            public void onItemDelete(int position) {
                if (!SClick.check(SClick.BUTTON_CLICK)) return;

                showDeleteConfirm(position);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initStateLayout() {
        mStateLayout.setErrorAndEmptyAction(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mStateLayout.showContentView();
                initData(null);
            }
        });
    }

    public void showDeleteConfirm(final int position) {
        new AlertDialog.Builder(getActivity())
                .setMessage(R.string.parking_delete_plate_confirm)
                .setPositiveButton(R.string.parking_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (!SClick.check(SClick.BUTTON_CLICK)) return;

                        mPresenter.deletePlate(position);
                    }
                }).setNegativeButton(R.string.parking_cancel, null)
                .create().show();
    }

    @Override
    public void showPlateEdit(final int position, String plate) {
        if (plate == null || plate.isEmpty()) {
            plate = "";
        }

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.parking_view_dialog_input, null, false);
        final EditText editText = view.findViewById(R.id.parking_view_dialog_input_et);
        editText.setText(plate);
        editText.setSelection(plate.length());
        AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setView(view)
                .setMessage(R.string.parking_add_plate_title)
                .setPositiveButton(R.string.parking_save, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (!SClick.check(SClick.BUTTON_CLICK)) return;

                        mPresenter.savePlate(position, editText.getText().toString());
                    }
                }).setNegativeButton(R.string.parking_cancel, null)
                .create();

        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                editText.requestFocus();
                editText.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
                    }
                }, 200);
            }
        });
        dialog.show();
    }

    @Override
    public void showLoading() {
        mStateLayout.showProgressView();
    }

    @Override
    public void showPlates(List<String> plates) {
        mAdapter.setData(plates);
        mStateLayout.showContentView();
    }

    @Override
    public void showEmpty() {
        mStateLayout.showEmptyView();
    }

    @Override
    public void showPlateFailure(String error) {
        mHUD.showErrorWithStatus(error);
    }

    @Override
    public void showPlateInfo(String plate, ParkingCardModel card) {
        Intent intent = new Intent(PARKING_ACTION_SHOW_PLATE_INFO);
        Map<String, String> param = new HashMap<>();
        param.put("plate", plate);
        if (card != null) {
            param.put("card_id", String.valueOf(card.id));
            param.put("card_number", card.cardNo);
            param.put("card_auto", String.valueOf(card.isAuto));
        }
        intent.putExtra("param", (Serializable) param);

        getActivity().sendBroadcast(intent);
    }

    @Override
    public void showDeleteFailure(String error) {
        mHUD.showErrorWithStatus(error);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (PARKING_ACTION_REFRESH_PLATE.equals(intent.getAction())) {
                mPresenter.getData();
            }
        }
    };
}
